package connect;

//public class Json2Rfc {
//}

import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoParameterList;
import com.sap.conn.jco.JCoTable;
import common.SAPConnUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
/**
 * @author Lida json to rfc
 */
public class Json2Rfc {
    public static String json2rfc(JSONObject jsonObject, String funcName) {
        JCoDestination destination = SAPConnUtil.connect();
        JCoFunction function = null;
        String result="";
        try {
            function = destination.getRepository().getFunction(funcName);
            JCoParameterList input = function.getImportParameterList();
            // 解析json
            for (Object k : jsonObject.keySet()) {
                Object v = jsonObject.get(k);
                // 如果内层是数组，则对应表参数
                if (v instanceof JSONArray) {
                    JSONArray jsonArray=JSONArray.fromObject(v);
                    JCoTable jCoTable=function.getTableParameterList().getTable((String)k);
                    for(Object object:jsonArray){//遍历数组
                        JSONObject jsObject=JSONObject.fromObject(object);
                        jCoTable.appendRow();//数组中每个元素添加一个行项目。
                        for (Object ak : jsObject.keySet()) {//遍历数组中元素的全部属性
                            Object av = jsObject.get(ak);
                            if(JSONNull.getInstance()!=av&&null!=av&&!av.equals(""))
                                jCoTable.setValue(ak.toString(), av.toString());
                        }
                    }
                } else {
                    input.setValue((String)k, v);
                }
            }
            function.execute(destination);
            JCoParameterList pexport = function.getExportParameterList();
            JCoParameterList texport = function.getTableParameterList();
//            String pstring=Xml2Json.xml2JSON(pexport.toXML());
//            String tstring=Xml2Json.xml2JSON(texport.toXML());
        } catch (Exception e) {
        }


        return result;
    }
}
